
const LoggerService = require('./service/logger');
const tencentcloud = require('tencentcloud-sdk-nodejs');
const EssbasicClient = tencentcloud.essbasic.v20210526.Client;

const clientConfig = {
  credential: {
    secretId: process.env.VUE_APP_SECRET_ID,
    secretKey: process.env.VUE_APP_SECRET_KEY,
  },
  region: '',
  profile: {
    httpProfile: {
      endpoint: 'essbasic.test.ess.tencent.cn',
    },
  },
};

// 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
// 实例化要请求产品的client对象,clientProfile是可选的
const cloudApiClient = new EssbasicClient(clientConfig);

const mergeAgent = (agent = {}) => ({
  ProxyAppId: agent.ProxyAppId,
  ProxyOrganizationOpenId: agent.ProxyOrganizationOpenId,
  ProxyOperator: {
    OpenId: agent.OpenId,
  },
  AppId: process.env.VUE_APP_CHANNEL_APP_ID,
});


// 转换大小写 toUpperCase  toLowerCase
function convertToCase(e, type = 'toLowerCase') {
  const isString = function (e) {
    const flag = typeof e === 'string';
    if (flag) {
      return e.trim();
    }
    return false;
  };

  const txt = isString(e);
  if (!txt) {
    console.error('参数不是字符串');
    return e;
  }

  if (!/^[A-Za-z]/.test(txt)) {
    console.error('参数去收尾空格后第一个字符不是字母');
    return e;
  }

  // 转换大小写参数错误默认到转成大写
  if (type && !['toUpperCase', 'toLowerCase'].includes(type)) {
    // type = 'toUpperCase';
    return e;
  }

  return txt.replace(/^\S/, s => s[type]());
}

function objectConvertToCase(obj, type = 'toLowerCase') {
  const newObj = {};
  // TODO:  递归遍历
  // eslint-disable-next-line no-restricted-syntax
  for (const key in obj) {
    newObj[convertToCase(key, type)] = obj[key];
  }
  return newObj;
}
// 清理引用缓存
function clearRequireCache(dirs = []) {
  Object.keys(require.cache).forEach(i => {
    dirs.forEach(dir => {
      if (i.includes(dir)) {
        delete require.cache[require.resolve(i)];
      }
    });
  });
}

const APPROVER_STATUS_TEXT = {
  PENDING: '待签署',
  ACCEPT: '已签署',
  REJECT: '拒绝',
  DEADLINE: '过期没人处理',
  CANCEL: '流程已撤回',
  STOP: '流程已终止',
  WAITPICKUP: '待领取',
  FILLPENDING: '待填写',
  FILLACCEPT: '填写完成',
  FILLREJECT: '拒绝填写',
  EXCEPTION: '异常',
};

const WORKER_CONTRACT_STATTUS = {
  WAITSIGN: ['INIT', 'PART', 'WILLEXPIRE'],
  PART: ['PART'],
  SIGNED: ['ALL'],
  FAILED: ['CANCEL', 'REJECT', 'DEADLINE', 'EXCEPTION', 'STOPPED'],
};

module.exports = {
  mergeAgent,
  clientConfig,
  logger: LoggerService.getInstance(),
  cloudApiClient,
  convertToCase,
  objectConvertToCase,
  clearRequireCache,
  APPROVER_STATUS_TEXT,
  WORKER_CONTRACT_STATTUS,
};

/**
 * logger 使用方式

logger.info({
  message: 'info....',
});
logger.info('info...')
logger.error({
  desc: 'xxxx'.
  ....,
})
logger.error('error....')

logger.log({
  type: 'callback',
  ...params
})
 */
